package com.efast.dmom.equipment.opc.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.efast.dmom.equipment.opc.client.OPCUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
//import com.efast.cafe.commponent.es.socketio.util.SocketEventUtils;

//@Service
public class EquipMonitorService {

//	@Autowired
//	private SocketEventUtils eventUtil;

	private Server server;

	private OPCConnector opcConnector;

	public static void main(String[] args) throws Exception {

		EquipMonitorService equipMonitor = new EquipMonitorService();

		equipMonitor.initConnection();

		// OPCUtil.checkHeartBeat(equipMonitor.server,OPCUtil.getItem(OPCElement.EQUIP6_STATUS));
		OPCUtil.sendHeartBeat(OPCUtil.getItem(OPCElement.EQUIP6_STATUS));

		Thread.sleep(30000);

		OPCUtil.stopHeartBeatSender();

		// OPCUtil.simulateRead(equipMonitor.server);
		// equipMonitor.doBroadcast();
		// equipMonitor.simulateWrite();
	}

	public void initConnection() throws Exception {

		opcConnector = OPCConnector.getInstance();

		if (!opcConnector.checkConnection()) {
			OPCConnector.initConnection();
		}

		this.server = opcConnector.getServer();
	}

	protected List<OPCEquipBean> getEquipStatus(Map<Group, Item[]> groupItems) throws Exception {

		List<OPCEquipBean> beanList = new ArrayList<OPCEquipBean>();

		if (server != null) {

			beanList = OPCUtil.read(groupItems);
		}
		return beanList;
	}

	public void doBroadcast() throws Exception {

		List<OPCEquipBean> beanList = getEquipStatus(OPCConnector.getInstance().getGroupBuilder().getGroupItems());

		JSONObject jsonObj = new JSONObject();

		jsonObj.put("EQUIP_LIST_STATUS", beanList);

		System.out.println(JSONObject.toJSONString(jsonObj, SerializerFeature.WriteMapNullValue));

//		List<String> idList = eventUtil.getAllOnline();
//
//		for (String uid : idList) {
//
//			eventUtil.pushMessage(uid, "status_broadcast_event",
//					JSONObject.toJSONString(jsonObj, SerializerFeature.WriteMapNullValue));
//		}

	}

}
